<?php
/**
 * SetupController
 * 
 * @author Grover Campos & Norelys Arias
 * @version 0.1
 */
class SetupController extends Gtux_Controller_Action
{

  /**
   * 
   */
  public function init ()
  {
    parent::init();
    $this->_helper->layout->setLayout('layout_setup');
  }

  /**
   * @see Zend_Controller_Action::preDispatch()
   *
   */
  public function preDispatch ()
  {
    if (! $this->_auth->hasIdentity())
    {
      if (! in_array($this->getRequest()->getActionName(), array(
        'login' , 'menu'
      )))
      {
        $this->_helper->redirector('login', 'setup');
      }
    }
  }

  /**
   * The default action - show the home page
   */
  public function indexAction ()
  {  // TODO Auto-generated SetupController::indexAction() default action
  }

  /**
   * Do the login to users
   *
   */
  public function loginAction ()
  {
    //$form = $this->getFormularioLogin();
    $form = new Gtux_Forms_Setup_Login();
    // asigno el formulario a la vista
    $this->view->assign('form', $form);
    if ($this->getRequest()->isPost())
    {
      if ($form->isValid($this->getRequest()->getPost()))
      {
        $username = $this->getRequest()->getPost('username');
        $password = $this->getRequest()->getPost('password');
        $entityFilter = new Zend_Filter_HtmlEntities();
        $username = $entityFilter->filter($username);
        $password = $entityFilter->filter($password);
        $this->_authAdapter->setIdentity($username)->setCredential($password);
        $result = $this->_auth->authenticate($this->_authAdapter);
        if (! $result->isValid())
        {
          $this->view->assign('error', true);
          $this->view->assign('mensajes', $result->getMessages());
        }
        else
        {
          $user = new Gtux_Model_User();
          $user->setUsername($username);
          $this->_session->Usuario = $user;
          $this->_helper->redirector('index');
        }
      }
      else
      {
        $this->view->assign('error', true);
        $this->view->assign('mensajes', $form->getErrorMessages());
      }
    }
  }

  /**
   * Do logout to user
   *
   */
  public function logoutAction ()
  {
    $this->_auth->clearIdentity();
    $this->_helper->redirector(array(
      'action' => 'index' , 'controller' => 'setup'
    ));
  }

  /**
   * Render the menu
   *
   */
  public function menuAction ()
  {
    $this->_helper->layout->disableLayout();
    if ($this->_auth->hasIdentity())
    {
      $this->view->assign('logeado', true);
    }
    else
    {
      $this->view->assign('logeado', false);
    }
  }

  /**
   * Muestra el inicio de los formularios
   *
   */
  public function formulariosAction ()
  {
    $var = new Gtux_Model_Variable();
    $this->_db = $var->getDbConn();
    $paso = $this->getRequest()->getParam('paso', 0);
    switch ($paso)
    {
      case 'crear':
        $tablas = $this->_db->listTables(); 
        $this->view->assign('tables_rs', $tablas);
        break;
      case 1:
        $tabla = $this->getRequest()->getParam('tabla');
        $this->formulario($tabla);
        break;
      case 6:
        $this->guardar_formulario();
        break;
      case 'listar':
      default:
        // @todo
        break;
    }
  }

  /**
   * Muestra las variables del sistema
   *
   */
  public function configurarAction ()
  {
    $valores = $this->_session->variables;
    //$this->_logger->info($valores);
    $editar  = $this->getRequest()->getParam('editar', 0);
    if ($editar)
    {
      $form = new Gtux_Forms_Setup_Configure(array('valores' => $valores));
      $this->view->assign('form', $form);
      if ($this->getRequest()->isPost())
      {
        if ($form->isValid($this->getRequest()->getPost()))
        {
          // host
          $variable = new Gtux_Model_Variable();
          $variable->setIdVariable(Gtux_Model_Variable::CONFIG_HOST);
          $variable->setValor($this->getRequest()->getPost('host'));
          $variable->save();
          // usuario
          $variable->setIdVariable(Gtux_Model_Variable::CONFIG_USUARIO);
          $variable->setValor($this->getRequest()->getPost('user'));
          $variable->save();
          // password
          $variable->setIdVariable(Gtux_Model_Variable::CONFIG_CLAVE);
          $variable->setValor($this->getRequest()->getPost('clave'));
          $variable->save();
          // base de datos
          $variable->setIdVariable(Gtux_Model_Variable::CONFIG_BASEDATOS);
          $variable->setValor($this->getRequest()->getPost('base_datos'));
          $variable->save();
          
          // recargo las nuevas variables
          $variable = new Gtux_Model_Variable();
          $coll     = new ArrayObject($variable->fetchAll());
          $this->_session->variables = $coll;
          
          $this->_helper->redirector('configurar', 'setup');
        }
      }
    }
    else
    {
      $this->view->assign('valores', $valores);
      $this->renderScript('setup' . DIRECTORY_SEPARATOR . 'configurar_ver.phtml');
    }
  }

  /**
   * Presenta la informacion del formulario
   * 
   * @param string $tabla
   */
  private function formulario ($tabla)
  {
    $entityFilter = new Zend_Filter_HtmlEntities();
    $tabla = $entityFilter->filter($tabla);
    if (0 >= strlen($tabla))
    {
      throw new InvalidArgumentException();
    }
    $tabla_info = $this->_db->describeTable($tabla);
    $formulario = Gtux_Model_Formulario::iniciarDeDescribe($tabla, $tabla_info);
    $formulario->setUser($this->_session->Usuario);
    
    $this->_session->formulario = $formulario;
    
    $frmGuardar = new Gtux_Forms_Setup_FormularioGuardar();
    
    $this->view->assign('frmGuardar', $frmGuardar);
    $this->view->assign('formulario', $formulario);
    $this->view->assign('tabla', $tabla);
    $this->renderScript('setup' . DIRECTORY_SEPARATOR . 'formulario.phtml');
  }
  
  /**
   * Guarda un formulario que se ha estado trabajando
   */
  private function guardar_formulario() 
  {
    $formulario = $this->_session->formulario; 
    if (!$formulario instanceof Gtux_Model_Formulario)
    {
      $this->_helper->redirector('formularios', 'setup');
    }
    $form = new Gtux_Forms_Setup_FormularioGuardar();
    if ($this->getRequest()->isPost())
    {
      if ($form->isValid($this->getRequest()->getPost()))
      {
        try
        {
          $flg = $formulario->save();
          $this->_session->formulario = $formulario;
          $this->view->assign('ok', ($flg) ? ('ok') : ('bad'));
        }
        catch (Exception $e)
        {
          $this->view->assign('fallo', $e->getMessage());
        }
      }
      else 
      {
        $this->view->assign('fallo', $form->getMessages());
      }
      $this->renderScript('setup' . DIRECTORY_SEPARATOR . 'guardar.phtml');
    }
    else 
    {
      $this->_helper->redirector('formularios', 'setup');
    }
  }
  
  /**
   * Lista los formularios existentes
   */
  private function listar_formularios() 
  {
    // @todo;
  }
}
?>